<?php

namespace app\admin\controller;

use app\admin\model\Api;
use app\admin\model\ApiField;
use app\admin\model\ApiParam;
use app\admin\model\ApiPrice;
use app\admin\model\ApiType;
use app\admin\model\MemberLevel;
use think\Request;

class ApiController extends BaseController
{
    public function index()
    {

        $Member = new MemberLevel();
        $level = $Member->select();
        $this->assign('level', $level);
        $ApiParam = ApiParam::all();
        $this->assign('ApiParam', $ApiParam);
        return $this->fetch();
    }

    /**
     * author：廖桂钦
     * eamil : artistCode@163.com
     * create time :2020/4/8
     * description[读取api 列表]
     */
    public function read()
    {
        $Api = new Api();
        $Api =$Api->with(['ApiField','ApiPrice']);
        $count = $Api->count();
        $data = $Api->page(input('get.page'), input('get.limit'))->select();
        return json(array('code' => 0, 'msg' => "", 'data' => $data, 'count' => $count));
    }


    /**
     * author：廖桂钦
     * eamil : artistCode@163.com
     * create time :2020/4/8
     */
    public function add(Request $request)
    {
        $Api = new Api();
        $data = $request->only(['api_name', 'price', 'api_type','cost_price','api_path','api_param_id']);

        $data['sign'] = md5(uniqid());
        $param = $request->only(['api_field','level']);
        $data = $Api->allowField(true)->save($data);
        if ($data) {
            $Api->ApiField()->saveAll($param['api_field']);
            $Api->ApiPrice()->saveAll($param['level']);
            return json(['code' => 0, 'msg' => '添加成功']);
        } else {
            return json(['code' => 500, 'msg' => '添加失败']);
        }
    }

    public function upd(Request $request)
    {
        $Api = (new Api());
        $data = $request->only(['api_name', 'api_type','cost_price','price','api_id','api_param_id','api_path']);
        $param = $request->only(['api_field','level']);
        $Api->isUpdate(true)->save($data);
        if ($Api) {
           if (isset($param['api_field'])){
               $Api->ApiField()->saveAll($param['api_field']);
           }
            $Api->ApiPrice()->saveAll($param['level']);
            return json(['code' => 0, 'msg' => '更新成功']);
        } else {
            return json(['code' => 500, 'msg' => '更新失败']);
        }
    }

    public function del(Request $request)
    {
        $Api = Api::get($request->param('api_id'))->delete();
        if ($Api) {
            ApiField::where('api_id',$request->param('api_id'))->delete();
            ApiPrice::where('api_id',$request->param('api_id'))->delete();
            return json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return json(['code' => 500, 'msg' => '删除失败']);
        }
    }

}
